<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划类型" prop="taskType">
        <el-select v-model="queryParams.taskType" placeholder="请选择计划类型" clearable>
          <el-option v-for="dict in task_task_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择计划状态" clearable>
          <el-option v-for="dict in task_task_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="工作人数" prop="employNum">
        <el-input v-model="queryParams.employNum" placeholder="请输入工作人数" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['base:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['base:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['base:task:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['base:task:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划编号" align="center" prop="id" />
      <el-table-column label="计划类型" align="center" prop="taskType">
        <template #default="scope">
          <dict-tag :options="task_task_type" :value="scope.row.taskType" />
        </template>
      </el-table-column>
      <el-table-column label="计划状态" align="center" prop="taskStatus">
        <template #default="scope">
          <dict-tag :options="task_task_status" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="工作人数" align="center" prop="employNum" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleDistribute(scope.row)"
            v-hasPermi="['base:task:edit']">分配</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['base:task:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改农事计划操作对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="计划类型" prop="taskType">
          <el-select v-model="form.taskType" placeholder="请选择计划类型">
            <el-option v-for="dict in task_task_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划状态" prop="taskStatus" v-if="form.id">
          <el-radio-group v-model="form.taskStatus">
            <el-radio v-for="dict in task_task_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="工作人数" prop="employNum">
          <el-input v-model="form.employNum" placeholder="请输入工作人数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openDis" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="计划编号" prop="taskId">
          <el-input v-model="form.taskId" placeholder="请输入计划编号" />
        </el-form-item> -->
        <el-form-item label="地块" prop="landId">
          <el-select v-model="form.landId" placeholder="">
            <el-option v-for="item in landList" :label="item.landName" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工姓名" prop="employName">
          <el-select v-model="form.employName" placeholder="">
            <div v-for="item in userList" :key="item.userId">
              <el-option v-if="item.postIds.includes(4)" :label="item.nickName" :value="item.nickName"></el-option>
            </div>
          </el-select>
        </el-form-item>
        <el-form-item label="工作量" prop="taskCount">
          <el-input v-model.number="form.taskCount" placeholder="请输入工作量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="distribute">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/base/task";
import { listLand } from "@/api/base/land"
import { changeUserStatus, listUser, resetUserPwd, delUser, getUser, updateUser, addUser, deptTreeSelect } from "@/api/system/user";
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/base/record";
const { proxy } = getCurrentInstance();
const { task_task_type, task_task_status } = proxy.useDict('task_task_type', 'task_task_status');

const taskList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskType: null,
    taskStatus: null,
    startTime: null,
    endTime: null,
    employNum: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询农事计划操作列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
const landList = ref([])
const getLandList = async () => {
  const res = await listLand()
  landList.value = res.rows
}
getLandList()
const userList = ref([])
const getUserList = async () => {
  const res = await listUser()
  userList.value = res.rows
}
getUserList()
// 取消按钮
function cancel() {
  open.value = false;
  openDis.value = false
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    taskType: null,
    taskStatus: null,
    startTime: null,
    endTime: null,
    createTime: null,
    remark: null,
    employNum: null,
    taskId: null,
    landId: null,
    employName: null,
    taskCount: null,
    remark: null
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加农事计划操作";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTask(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改农事计划操作";
  });
}

const openDis = ref(false)
const handleDistribute = async(row) => {
const res=await listRecord({taskId:row.id})
if(res.rows.length==row.employNum){
  proxy.$modal.msgError("分配人员已超过工作人数")
  return
}
  reset();
  form.value.taskId = row.id
  title.value = "分配计划";
  openDis.value = true
}
const distribute = () => {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      addRecord(form.value).then(response => {
        proxy.$modal.msgSuccess("分配成功");
        openDis.value = false;
        form.value.taskStatus=1
        form.value.id=form.value.taskId
        updateTask(form.value).then(response => {
          open.value = false;
          getList();
        });
        
      })
    }
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除农事计划操作编号为"' + _ids + '"的数据项？').then(function () {
    return delTask(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}

getList();
</script>
